package com.hunttown.mes.manage.controller._erp;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.qcloud.qcloudcos.CosConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportPurchaseDTO;
import com.hunttown.mes.rpc.domain.TransportPurchaseDetailDTO;
import com.hunttown.mes.rpc.domain.TransportPurchaseDocDTO;
import com.hunttown.mes.rpc.domain.enums.pay.ReceiveWayEnum;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDetailDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDocDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-01-28 11:16:52
 */
@Controller
@RequestMapping(value = "/erp/purchase-doc")
public class PurchaseDocController {

    private final static Logger logger = LoggerFactory.getLogger(PurchaseDocController.class);

    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportPurchaseDocManageService purchaseDocService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final TransactionService transactionService;
    private final WorkflowApplyLineManageService applyLineService;
    private final WorkflowApplyManageService applyManageService;
    private final WorkflowBusinessNodeManageService businessNodeService;

    @Autowired
    public PurchaseDocController(TransportPurchaseDocManageService purchaseDocService, AnalysisManageManageService manageService, ModelService modelService, TransportPurchaseManageService purchaseService, TransportPurchaseDetailManageService purchaseDetailService, TransactionService transactionService, WorkflowApplyLineManageService applyLineService, WorkflowApplyManageService applyManageService, WorkflowBusinessNodeManageService businessNodeService) {
        this.purchaseDocService = purchaseDocService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.purchaseService = purchaseService;
        this.purchaseDetailService = purchaseDetailService;
        this.transactionService = transactionService;
        this.applyLineService = applyLineService;
        this.applyManageService = applyManageService;
        this.businessNodeService = businessNodeService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportPurchaseDocDTOQuery dtoQuery) {

        //region 显示标题
        String showTitle = "未知";
        if (dtoQuery.getPurchaseType() == 1) {
            showTitle = "配件";
        }
        if (dtoQuery.getPurchaseType() == 2) { //采购
            showTitle = "物料";
        }
        model.addAttribute("showTitle", showTitle);
        //endregion

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        // 采购日期（初始化 30天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(30), DateConvertUtils.getPastDate(0)));
        }

        //dtoQuery.setStopFlag(0);    //是否显示撤回订单
        dtoQuery.setOrderBy("order by id desc");
        Page<TransportPurchaseDocDTO> dataPage = purchaseDocService.getForPage(dtoQuery);

        for (TransportPurchaseDocDTO item : dataPage.getItems()) {
            item.setCompanyName(modelService.getCompanyName(item.getCompanyId()));
            item.setPurchaseCn(modelService.getManageName(item.getPurchaser()));

            //region 是否可以操作
            item.setCanExec(0);

            //只判断审核中，采购中和已入库不能改动
            if (item.getStatus() == 0) {
                //必须是[自己的]并且未进入[审批阶段]
                int nodesign = applyLineService.getCurrLineNodeSignIdByApplyId(item.getApplyId());
                if (item.getAdminId().equals(curr_obj.getId()) && nodesign == 1) {
                    item.setCanExec(1);
                }
            }
            //endregion
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //采购人
        modelService.getManagerPage(model);

        //供应商
        modelService.getCompayPage(model, 2);

        //采购日期
        if (StringUtils.isNotBlank(dtoQuery.getDaterange())) {
            String[] date = dtoQuery.getDaterange().split("~");
            if (date.length == 2) {
                model.addAttribute("startDate", date[0].trim());
                model.addAttribute("endDate", date[1].trim());
            }
        }

        return "erp/purchase-doc/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model        model模型
     * @param id           主键id
     * @param purchaseType 采购类型：1汽车配件 2日常采购
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id, Integer purchaseType) {
        id = (id == null ? 0 : id);

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        TransportPurchaseDocDTO obj;

        if (id > 0) {
            obj = purchaseDocService.getById(id);
            obj.setIsUpload(obj.getPurchaseDoc());

            //region 是否有权操作

            //1.判断是否是自己的
            if (!obj.getAdminId().equals(curr_obj.getId())) {
                throw new RuntimeException("你无权对此采购单进行编辑！");
            }

            //2.判断是否进入了审批阶段
            int nodesign = applyLineService.getCurrLineNodeSignIdByApplyId(obj.getApplyId());
            if (nodesign > 1) {
                throw new RuntimeException("此采购单已进入审批环节，无法进行编辑！");
            }
            //endregion

            //region 获取采购明细
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(179);
            detailQuery.setPurId(id);
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);
            for (TransportPurchaseDetailDTO item : detailPage.getItems()) {
                TransportPurchaseDTO dto = purchaseService.getFromCacheId(item.getPartId());
                if (dto != null) {
                    item.setPartName(dto.getPartName());
                    item.setPartNo(dto.getPartNo());
                    item.setSpecialName(dto.getSpecialName());
                }
            }
            model.addAttribute("partsDetailList", detailPage.getItems());
            //endregion

            //region 获取已上传文件
            modelService.getUploadPage(model, obj.getPurchaseDoc());
            model.addAttribute("mainPicId", 0); //主图
            //endregion

        } else {
            obj = new TransportPurchaseDocDTO();
            obj.setId(0);
            obj.setPurchaseName(String.format("%s的（请简写物料名称）采购单", curr_obj.getNickName()));
            obj.setPurchaseNo(GeneralUtils.GenTimeSeries(4, null, null));
            obj.setPurchaseType(purchaseType);
            obj.setBxId(0);
            obj.setApplyId(0);
            obj.setRelationId(0);
            obj.setAmount(BigDecimal.ZERO);
            obj.setTaxRate(BigDecimal.ZERO);
            obj.setTax(BigDecimal.ZERO);
            obj.setPurchaseDate(new Date());
            obj.setExpressFee(BigDecimal.ZERO);
            obj.setPurchaser(curr_obj.getId());
        }
        model.addAttribute("Obj", obj);

        //供应商
        modelService.getCompayPage(model, 2);

        //付款单位
        modelService.getCompayPage(model, 7, null, "receivePayList");

        //付款方式
        model.addAttribute("receiveWayList", ReceiveWayEnum.getEnumList());

        //获取采购人、签收人
        modelService.getManagerPage(model);

        //物流公司
        modelService.getCatalogPage(model, 30, "expressList");

        //region 文件上传使用
        model.addAttribute("uploadTableName", "transport_purchase_doc");
        model.addAttribute("uploadRecordId", obj.getId());
        model.addAttribute("labelTips", "采购合同");
        model.addAttribute("btnTips", "上传合同");
        model.addAttribute("modalTips", "合同上传");

        String uploadPrefix = CosConstants.getStorageFolder(null);
        model.addAttribute("uploadPrefix", uploadPrefix);
        //endregion

        //region 显示标题
        String showTitle = "未知";
        if (purchaseType == 1) {
            showTitle = "配件";
        }
        if (purchaseType == 2) {
            showTitle = "物料";
        }
        model.addAttribute("showTitle", showTitle);
        //endregion

        return "erp/purchase-doc/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportPurchaseDocDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        int docid = 0; //新生成的采购单ID
        int doc_apply = 0; //新生成的审批ID

        try {
            if (objDTO.getPurchaser() == 0) {
                map = OperateCode.CompositionResult(map, -10, "请选择采购人！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //日期
            objDTO.setPurchaseDate(DateConvertUtils.strToDate(objDTO.getPurchaseDateSr()));
            objDTO.setSendDate(DateConvertUtils.strToDate(objDTO.getSendDateSr()));
            objDTO.setSignDate(DateConvertUtils.strToDate(objDTO.getSignDateSr()));

            //处理上传ID
            objDTO.setPurchaseDoc(FormatUtils.formatCommas(objDTO.getIsUpload()));

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            //流程业务代码
            String businessNameEn = "";

            if (objDTO.getId() == null || objDTO.getId() <= 0) { //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);

                //其它初始值
                objDTO.setProId(0);
                objDTO.setIsCompleteInstore(0);
                objDTO.setStatus(0);

                objDTO = purchaseDocService.insert(objDTO);

                if (objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                docid = objDTO.getId();

                Map<String, String> param = new HashMap<>();
                param.put("applyTitle", objDTO.getPurchaseName().replace("采购", "采购审批"));
                param.put("firstExector", modelService.getUserIdByAdminId(objDTO.getPurchaser()) + ""); //[改版后]审批人走的是会员系统

                if (objDTO.getPurchaseType() == 1) {
                    //[1].配件采购
                    businessNameEn = "purchase_apply";
                } else {
                    //[2].物料采购
                    businessNameEn = "purchase_ready";
                }

                Integer applyId = transactionService.createApplyWithout(businessNameEn, "transport_purchase_doc", objDTO.getId(), objDTO.getAdminId(), param);
                if (applyId > 0) {
                    doc_apply = applyId;

                    //更新采购表中的applyId
                    TransportPurchaseDocDTO updateDto = new TransportPurchaseDocDTO();
                    updateDto.setId(objDTO.getId());
                    updateDto.setApplyId(applyId);
                    purchaseDocService.updateInfoById(updateDto);

                } else {
                    //审批流程生成失败 删除已经生成的采购单
                    purchaseDocService.delete(objDTO.getId());

                    //程序终止，返回失败信息
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else { //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = purchaseDocService.updateInfoById(objDTO);

                if (isNext) {

                    //region //设置第1审批人
                    if (objDTO.getApplyId() != null && objDTO.getApplyId() > 0) {
                        Map<Integer, Integer> replaceMap = new HashMap<>();
                        replaceMap.put(1, modelService.getUserIdByAdminId(objDTO.getPurchaser()));
                        transactionService.setExector(objDTO.getApplyId(), replaceMap);
                    }
                    //endregion

                } else {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region 操作完成后判断金额是否大于300，如果大于300则启用经理审批
            businessNodeService.handleJudgeApply(businessNameEn, 1, objDTO.getAmount(), doc_apply);
            //endregion

            //region 采购明细表.保存成功后更新采购明细表
            String[] f_id = request.getParameterValues("f_id");
            String[] f_partid = request.getParameterValues("f_partid");
            String[] f_rstorecount = request.getParameterValues("f_rstorecount");
            String[] f_rprice = request.getParameterValues("f_rprice");
            String[] f_rcount = request.getParameterValues("f_rcount");
            String[] f_ramount = request.getParameterValues("f_ramount");

            //1.获取已保存的采购明细
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(179);
            detailQuery.setPurId(objDTO.getId());
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> oldPlanPage = purchaseDetailService.getForPage(detailQuery);

            //2. 保存到数据库
            if (f_id != null && f_id.length > 0) {

                List<Integer> newPlanIds = new ArrayList<>(); //提交上来的，已保存过的ID
                TransportPurchaseDetailDTO insert;
                Date default_date = DateConvertUtils.strToDate("1990-01-01");

                for (int i = 0; i < f_id.length; i++) {
                    if (Integer.parseInt(f_rcount[i]) <= 0) {
                        continue;
                    }

                    insert = new TransportPurchaseDetailDTO();
                    insert.setParentId(0);
                    insert.setTableId(179);
                    insert.setRecordId(objDTO.getId());
                    insert.setPurchaseType(objDTO.getPurchaseType());
                    insert.setPartId(Integer.parseInt(f_partid[i]));
                    insert.setProId(0);
                    insert.setPurId(objDTO.getId());
                    insert.setOpType(1);
                    insert.setrPurchaseType(2);
                    insert.setrPurchaser(objDTO.getPurchaser());
                    insert.setrCompanyId(objDTO.getCompanyId());
                    insert.setrLinkName(objDTO.getLinkName());
                    insert.setrLinkMobile(objDTO.getLinkMobile());
                    insert.setrPayCompanyId(objDTO.getPayCompanyId());
                    insert.setrPayWay(objDTO.getPayWay());
                    insert.setrPrice(new BigDecimal(f_rprice[i]));
                    insert.setrCount(Integer.parseInt(f_rcount[i]));
                    insert.setrInCount(0);
                    insert.setrAmount(new BigDecimal(f_ramount[i]));
                    insert.setrTaxRate(objDTO.getTaxRate());
                    insert.setrTax(insert.getrAmount().multiply(insert.getrTaxRate()));
                    insert.setrStoreCount(Integer.parseInt(f_rstorecount[i]));
                    insert.setrPurchaseDate(objDTO.getPurchaseDate());
                    insert.setrInDate(default_date);
                    insert.setrSalePrice(BigDecimal.ZERO);
                    insert.setrMarketPrice(BigDecimal.ZERO);
                    insert.setrStorePrice(BigDecimal.ZERO);
                    insert.setcOutType(0);
                    insert.setcNoOrder(0);
                    insert.setcStoreCount(0);
                    insert.setcCount(0);
                    insert.setcCountAll(0);
                    insert.setcCountReal(0);
                    insert.setcCountReturn(0);
                    insert.setcCountNouse(0);
                    insert.setcRepairId(0);
                    insert.setcCarId(0);
                    insert.setcDriverId(0);
                    insert.setcUserId(0);
                    insert.setcOutDate(default_date);
                    insert.setsCount(0);
                    insert.setsAdminId(0);
                    insert.setsDate(default_date);
                    insert.setReviewer(0);
                    insert.setReviewDate(default_date);
                    insert.setReviewStatus(0);
                    insert.setStatus(0);
                    insert.setBxId(objDTO.getBxId());
                    insert.setApplyId(doc_apply);
                    insert.setRelationId(objDTO.getRelationId());
                    insert.setAdminId(curr_obj.getId());
                    insert.setCreateTime(new Date());
                    insert.setStopFlag(0);
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_id[i]);
                    if (id > 0) {
                        //更新
                        newPlanIds.add(id);
                        insert.setId(id);
                        purchaseDetailService.updateInfoById(insert);
                    } else {
                        //插入
                        purchaseDetailService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (TransportPurchaseDetailDTO item : oldPlanPage.getItems()) {
                    if (!newPlanIds.contains(item.getId())) {
                        purchaseDetailService.delete(item.getId());
                    }
                }
            }
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            if (docid > 0) {
                //删除已经生成的采购单
                purchaseDocService.delete(docid);

                //删除审批单
                applyManageService.delete(doc_apply);
            }

            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = purchaseDocService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = purchaseDocService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportPurchaseDocDTO obj = new TransportPurchaseDocDTO();
        obj.setId(id);

        if (id > 0) {
            obj = purchaseDocService.getById(id);
        }
        purchaseDocService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 完善快递发货信息
    @RequestMapping(value = "/editSendInfo", method = RequestMethod.POST)
    public String editSendInfo(HttpServletRequest request, Model model, Integer id) {
        if (id == null || id <= 0) {
            model.addAttribute("returnCode", 0);
            model.addAttribute("returnMessage", "无效请求");
            return "erp/purchase-doc/update-express-modal";
        }

        //获取采购单
        TransportPurchaseDocDTO obj = purchaseDocService.getById(id);
        if (obj.getSendDateSr().equals("1990-01-01")) {
            obj.setSendDate(new Date());
        }
        if (obj.getSignDateSr().equals("1990-01-01")) {
            obj.setSignDate(new Date());
        }

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        obj.setSignId(curr_obj.getId());

        model.addAttribute("Obj", obj);

        //获取采购人、签收人
        modelService.getManagerPage(model);

        //物流公司
        modelService.getCatalogPage(model, 30, "expressList");

        return "erp/purchase-doc/update-express-modal";
    }

    @RequestMapping(value = "/saveSendInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveSendInfo(HttpServletRequest request, Integer id, Integer expressId, String expressNo,
                                            String sendDateSr, String expressLink, String expressMobile, BigDecimal expressFee,
                                            Integer signId, String signDateSr, String signRemark) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (id == null || id <= 0) {
            map.put("returnMessage", "快递发货信息更新失败");
            return map;
        }

        TransportPurchaseDocDTO update = new TransportPurchaseDocDTO();
        update.setId(id);
        update.setExpressId(expressId);
        update.setExpressNo(expressNo);
        update.setSendDate(DateConvertUtils.strToDate(sendDateSr));
        update.setExpressLink(expressLink);
        update.setExpressMobile(expressMobile);
        update.setExpressFee(expressFee);
        update.setSignId(signId);
        update.setSignDate(DateConvertUtils.strToDate(signDateSr));
        update.setSignRemark(signRemark);
        boolean isNext = purchaseDocService.updateInfoById(update);

        if (isNext) {
            map.put("returnMessage", "发货信息更新成功");
        } else {
            map.put("returnMessage", "更新失败");
        }

        return map;
    }
    //endregion

    //region 采购入库
    @RequestMapping(value = "/inStorage", method = RequestMethod.GET)
    public String inStorage(HttpServletRequest request, Model model, Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("未查询到当前采购单！");
        }

        TransportPurchaseDocDTO purchaseDocDTO = purchaseDocService.getById(id);
        purchaseDocDTO.setCompanyName(modelService.getCompanyName(purchaseDocDTO.getCompanyId()));
        purchaseDocDTO.setPurchaseCn(modelService.getManageName(purchaseDocDTO.getPurchaser()));
        purchaseDocDTO.setPayCompanyName(modelService.getCompanyName(purchaseDocDTO.getPayCompanyId()));
        purchaseDocDTO.setPayWayName(ReceiveWayEnum.getEnumByKey(purchaseDocDTO.getPayWay()));
        purchaseDocDTO.setExpressName(modelService.getCatalogName(purchaseDocDTO.getExpressId()));
        purchaseDocDTO.setSignCn(modelService.getManageName(purchaseDocDTO.getSignId()));
        model.addAttribute("purchaseDocObj", purchaseDocDTO);

        //region 获取采购明细（获取未入库的：采购数量 > 已入库数量）
        TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
        detailQuery.setTableId(179);
        detailQuery.setPurId(purchaseDocDTO.getId());
        detailQuery.setNoInStore(1);
        detailQuery.setStopFlag(0);
        detailQuery.setPageSize(100);
        Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);
        for (TransportPurchaseDetailDTO item : detailPage.getItems()) {
            TransportPurchaseDTO dto = purchaseService.getFromCacheId(item.getPartId());
            if (dto != null) {
                item.setPartName(dto.getPartName());
                item.setPartNo(dto.getPartNo());
                item.setSpecialName(dto.getSpecialName());
                item.setrCount(item.getrCount() - item.getrInCount());
                item.setrInCount(item.getrCount());
            }
        }
        model.addAttribute("partsDetailList", detailPage.getItems());
        //endregion

        //region 获取已上传附件
        modelService.getUploadPage(model, purchaseDocDTO.getPurchaseDoc());
        //endregion

        return "erp/purchase-doc/edit-instore";
    }

    @RequestMapping(value = "/saveInStore", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveInStore(HttpServletRequest request, Integer id, Integer isCompleteInstore) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (id == null || id <= 0) {
            map.put("returnMessage", "保存入库失败");
            return map;
        }

        isCompleteInstore = isCompleteInstore == null ? 0 : isCompleteInstore;

        //入库
        String[] f_id = request.getParameterValues("f_id");
        String[] f_in_rcount = request.getParameterValues("f_in_rcount");
        String[] f_r_shelves = request.getParameterValues("f_r_shelves");
        String[] f_r_shelves_level = request.getParameterValues("f_r_shelves_level");
        String[] f_r_shelves_location = request.getParameterValues("f_r_shelves_location");

        if (f_id != null && f_id.length > 0) {
            for (int i = 0; i < f_id.length; i++) {
                if (f_in_rcount[i] == null) {
                    continue;
                }

                int _id = Integer.parseInt(f_id[i]);
                int _in_count = Integer.parseInt(f_in_rcount[i]);
                if (_in_count <= 0) {
                    continue;
                }

                int _total_in_count = 0; //总入库数量

                //1、入库
                TransportPurchaseDetailDTO detail = purchaseDetailService.getById(_id);
                if (detail.getrInCount() > detail.getrCount()) {
                    continue; //已经入过了，没有可入的了
                }

                _total_in_count = _in_count + detail.getrInCount();

                detail.setId(0);
                detail.setTableId(50); //物料表
                detail.setRecordId(0);
                detail.setOpType(1);
                detail.setrPurchaseType(1);
                detail.setrCount(_in_count);
                detail.setrInCount(0);
                detail.setrAmount(detail.getrPrice().multiply(BigDecimal.valueOf(detail.getrCount())));
                detail.setrInDate(new Date());
                detail.setrShelves(f_r_shelves[i]);
                detail.setrShelvesLevel(f_r_shelves_level[i]);
                detail.setrShelvesLocation(f_r_shelves_location[i]);
                purchaseDetailService.insert(detail);

                //2、更新已入库数量
                TransportPurchaseDetailDTO u_dto = new TransportPurchaseDetailDTO();
                u_dto.setId(_id);
                u_dto.setrInCount(_total_in_count);
                purchaseDetailService.updateInfoById(u_dto);
            }
        }

        //3、入库完成以后判断是否已经全部入库
        if (isCompleteInstore == 0) {
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(179);
            detailQuery.setPurId(id);
            detailQuery.setNoInStore(1);
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);
            if (detailPage.getItems().size() == 0) {
                isCompleteInstore = 1;
            }
        }

        //保存是否已全部入库
        //4、如果已全部入库，则还需要更新状态为：10已入库
        TransportPurchaseDocDTO update = new TransportPurchaseDocDTO();
        update.setId(id);
        update.setIsCompleteInstore(isCompleteInstore);
        if (isCompleteInstore == 1) {
            update.setStatus(10);
        }
        purchaseDocService.updateInfoById(update);


        map.put("returnCode", 1);
        map.put("returnMessage", "入库完成");
        return map;
    }
    //endregion
}